<template>
  <div class="encyclopedia-portal">
    <!-- 搜索栏 -->
    <div class="search-section">
      <el-autocomplete
        v-model="searchKeyword"
        placeholder="请输入搜索关键词"
        :fetch-suggestions="querySearchAsync"
        @select="handleSearch"
        @keyup.enter.native="handleSearch"
      >
        <template #append>
          <el-button icon="Search" @click="handleSearch"/>
        </template>
      </el-autocomplete>
      
      <!-- 搜索历史 -->
      <div class="search-history" v-if="searchHistory.length > 0">
        最近搜索：
        <el-button type="text" icon="Delete" @click="removeSearchHistory" style="margin-right: 10px;"/>
        <el-tag
          v-for="(history, index) in searchHistory"
          :key="index"
          type="info"
          @click="searchKeyword = history; handleSearch()"
        >
          {{ history }}
        </el-tag>
      </div>
      
      <!-- 热门关键词 -->
      <div class="hot-keywords" v-if="hotKeywords.length > 0">
        热门搜索：
        <el-tag
          v-for="(keyword, index) in hotKeywords"
          :key="index"
          type="info"
          @click="handleHotKeywordClick(keyword)"
        >
          {{ keyword.keyword }} ({{ keyword.count }})
        </el-tag>
      </div>
    </div>

    <!-- 分类导航 -->
    <div class="category-tree">
      <h3>分类导航</h3>
      <el-tree
        :data="categoryTree"
        :props="treeProps"
        @node-click="handleCategorySelect"
      />
    </div>

    <!-- 热门词条 -->
    <div class="hot-entries">
      <h3>热门词条</h3>
      <div class="entry-list">
        <div 
          v-for="entry in hotEntries"
          :key="entry.id"
          class="entry-card"
          @click="navigateToEntry(entry)"
        >
          <h4>{{ entry.title }}</h4>
          <p class="summary">{{ entry.summary }}</p>
          <div class="meta">
            <span>👁️ {{ entry.view_count }}</span>
            <span>⭐ {{ entry.favorite_count }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 最新词条 -->
    <div class="latest-entries">
      <h3>最新更新</h3>
      <el-timeline>
        <el-timeline-item
          v-for="entry in latestEntries"
          :key="entry.id"
          :timestamp="formatTime(entry.created_at)"
        >
          <el-card @click="navigateToEntry(entry)">
            <h4>{{ entry.title }}</h4>
            <p class="summary">{{ entry.summary }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { debounce } from 'lodash-es'
import {
  getHotKeywords,
  getCategoryTree,
  getHotEntries,
  getLatestEntries,
  getSearchHistory,
  deleteSearchHistory,
  getSearchSuggestions,
} from '/@/api/encyclopedia'

const router = useRouter()

// 搜索相关
const searchKeyword = ref('')
const hotKeywords = ref([])
const searchHistory = ref([])

// 分类树
const categoryTree = ref([])
const treeProps = {
  children: 'children',
  label: 'name'
}

// 内容数据
const hotEntries = ref([])
const latestEntries = ref([])

// 初始化加载数据
onMounted(async () => {
  try {
    const [hotRes, categoryRes, latestRes] = await Promise.all([
      getHotEntries(),
      getCategoryTree(),
      getLatestEntries()
    ])
    await loadSearchHistory()
    
    hotEntries.value = hotRes.data
    categoryTree.value = categoryRes.data
    latestEntries.value = latestRes.data
    
    // 加载热门关键词
    const keywordRes = await getHotKeywords()
    hotKeywords.value = keywordRes.data
  } catch (error) {
    console.error('初始化数据加载失败:', error)
  }
})

// 时间格式化
const formatTime = (timeString) => {
  return dayjs(timeString).format('YYYY-MM-DD HH:mm')
}

// 搜索处理
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      path: '/search',
      query: { keyword: searchKeyword.value.trim() }
    })
  }
}

// 移除搜索历史
const removeSearchHistory = async (index) => {
  try {
    await deleteSearchHistory(index)
    searchHistory.value = []
    const keywordRes = await getHotKeywords()
    hotKeywords.value = keywordRes.data
  } catch (error) {
    console.error('删除搜索历史失败:', error)
  }
}

// 异步搜索建议
const querySearchAsync = debounce(async (queryString, cb) => {
  if (queryString) {
    try {
      const res = await getSearchSuggestions(queryString)
      const results = res.data.map(item => ({
        value: item.title,
        id: item.id
      }))
      cb(results)
    } catch (error) {
      console.error('获取搜索建议失败:', error)
      cb([])
    }
  }
}, 300)
// 新增方法 - 处理热门关键词点击
const handleHotKeywordClick = (keyword) => {
  searchKeyword.value = keyword.keyword
  // 记录热门关键词的点击次数
  recordKeywordClick(keyword.id)
  handleSearch()
}

// 新增方法 - 加载搜索历史
const loadSearchHistory = async () => {
  try {
    const res = await getSearchHistory()
    searchHistory.value = res.data.map(item => item.keyword)
  } catch (error) {
    console.error('获取搜索历史失败:', error)
  }
}

// 分类选择
const handleCategorySelect = (nodeData) => {
  router.push({
    path: `/category/${nodeData.id}`
  })
}

// 跳转词条详情
const navigateToEntry = (entry) => {
  router.push(`/entry/${entry.id}`)
}
</script>

<style scoped>
.encyclopedia-portal {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-section {
  margin-bottom: 40px;
  :deep(.el-input) {
    width: 600px;
    margin-bottom: 10px;
  }
}

.hot-keywords {
  margin-top: 15px;
  .el-tag {
    margin-right: 10px;
    margin-bottom: 5px;
    cursor: pointer;
    &:hover {
      background-color: var(--el-color-primary-light-9);
    }
  }
}

.search-history {
  margin-top: 10px;
  .el-tag {
    margin-right: 8px;
    margin-bottom: 5px;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      transform: scale(1.05);
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    }
  }
}

.category-tree {
  margin-bottom: 40px;
  h3 {
    color: var(--el-color-primary);
    margin-bottom: 15px;
  }
}

.entry-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.entry-card {
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: transform 0.2s;
  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .summary {
    color: var(--el-text-color-secondary);
    font-size: 0.9em;
    margin: 10px 0;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .meta {
    display: flex;
    justify-content: space-between;
    color: var(--el-color-info);
    font-size: 0.8em;
  }
}

.latest-entries {
  margin-top: 40px;
  :deep(.el-timeline-item) {
    cursor: pointer;
    .el-card {
      transition: transform 0.2s;
      &:hover {
        transform: translateX(10px);
      }
    }
  }
  h3 {
    color: var(--el-color-primary);
    margin-bottom: 15px;
  }
}
.hot-entries {
  margin-bottom: 40px;
  h3 {
    color: var(--el-color-primary);
    margin-bottom: 15px;
  }
}
</style>
